package com.jason.lucene.example.search;

import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.WildcardQuery;
import org.junit.Assert;
import org.junit.Test;

/**
 * 通配符查询测试 , 通配符查询可以使用不完整的、缺少某些字母的项进行查询。
 * lucene 使用了两个标准的通配符 * 代表 0 个或多个字母 ，
 * ? 代表 0 个或者多个字母
 *
 * @author he peng
 * @create 2017/12/6 18:45
 * @see
 */
public class WildcardQueryTest extends BaseQueryTest {

    @Test
    public void testWildcard() throws Exception {
        indexingSingleFieldDocs(new Field[]{
                new Field("contents" , "wild" , TextField.TYPE_STORED) ,
                new Field("contents" , "child" , TextField.TYPE_STORED) ,
                new Field("contents" , "mild" , TextField.TYPE_STORED) ,
                new Field("contents" , "mildew" , TextField.TYPE_STORED)
        });

        // lucene 使用了两个标准的通配符 * 代表 0 个或多个字母 ，* ? 代表 0 个或者多个字母
        //
        WildcardQuery wildcardQuery = new WildcardQuery(new Term("contents" , "?ild*"));
        IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(this.dir));
        TopDocs topDocs = searcher.search(wildcardQuery, 1000);
        for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
            System.err.println("hit doc =====> " + searcher.doc(scoreDoc.doc));
        }

        Assert.assertEquals("child no match" , 3 , topDocs.totalHits);
        Assert.assertEquals("score the same" ,
                    topDocs.scoreDocs[0].score , topDocs.scoreDocs[1].score , 0.0);
        Assert.assertEquals("score the same" ,
                topDocs.scoreDocs[1].score , topDocs.scoreDocs[2].score , 0.0);

    }


}
